// Fill out your copyright notice in the Description page of Project Settings.


#include "Core/XG_GameInstanceSubsystem.h"

#include "WebSocketsModule.h"
#include "Log/FTLog.h"

bool UXG_GameInstanceSubsystem::ShouldCreateSubsystem(UObject* Outer) const
{
	return true;
}

void UXG_GameInstanceSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
	Super::Initialize(Collection);
}

void UXG_GameInstanceSubsystem::Deinitialize()
{
	Super::Deinitialize();
}

void UXG_GameInstanceSubsystem::Tick(float DeltaTime)
{
}

bool UXG_GameInstanceSubsystem::IsTickable() const
{
	return true;
}

TStatId UXG_GameInstanceSubsystem::GetStatId() const
{
	RETURN_QUICK_DECLARE_CYCLE_STAT(UXG_GameInstanceSubsystem,STATGROUP_Tickables);
}

void UXG_GameInstanceSubsystem::CreateSocket()
{
	FModuleManager::Get().LoadModuleChecked("WebSockets");

	FString BaseString = TEXT("");

	FString TS = TEXT("1512041814");
	TS=FString::FromInt(FDateTime::Now().UtcNow().ToUnixTimestamp());
	BaseString = AppId + TS;

	FString MD5BaseString =FMD5::HashAnsiString(*BaseString);
	
	FSHAHash Hash;
	FSHA1 SHA1;
	SHA1.HMACBuffer(TCHAR_TO_ANSI(*APIKey),APIKey.Len(),TCHAR_TO_ANSI(*MD5BaseString),MD5BaseString.Len(),Hash.Hash);
	FString Signa=FBase64::Encode(Hash.Hash,20);
	Signa = Signa.Replace(TEXT("="),TEXT("%3D"));

	ServerProtected = TEXT("ws");
	ServerURL = TEXT("ws://rtasr.xfyun.cn/v1/ws?");
	//	ws://rtasr.xfyun.cn/v1/ws?appid=595f23df&ts=1512041814&signa=IrrzsJeOFk1NGfJHW6SkHUoN9CU=&pd=edu
	ServerURL += TEXT("appid=") + AppId;
	ServerURL += TEXT("&ts=") + TS;
	ServerURL += TEXT("&signa=") + Signa;
	ServerURL += TEXT("&pd=edu");
	
	webSocket = FWebSocketsModule::Get().CreateWebSocket(ServerURL,ServerProtected);
	
	webSocket->OnConnected().AddUObject(this,&ThisClass::OnConnected);
	webSocket->OnConnectionError().AddUObject(this,&ThisClass::OnConnectionError);
	webSocket->OnClosed().AddUObject(this,&ThisClass::OnClosed);
	webSocket->OnMessage().AddUObject(this,&ThisClass::OnMessage);
	webSocket->OnMessageSent().AddUObject(this,&ThisClass::OnMessageSent);
	
	webSocket->Connect();
}

void UXG_GameInstanceSubsystem::CloseSocket()
{
	if (webSocket.IsValid() && webSocket->IsConnected())
	{
		webSocket->Close();
	}
}

void UXG_GameInstanceSubsystem::OnConnected()
{
	LOG_WITH_LOCATION(TEXT("Connected On WebSocket"));
}

void UXG_GameInstanceSubsystem::OnConnectionError(const FString& ErrorText)
{
	LOG_WITH_LOCATION_ERROR(TEXT("Error %s"),*ErrorText);
}

void UXG_GameInstanceSubsystem::OnClosed(int32 StatusCode, const FString& ReasonText, bool bwasClean)
{
	LOG_WITH_LOCATION_WARNING(TEXT("%d Closed %s On WebSocket"),StatusCode,*ReasonText);
}

void UXG_GameInstanceSubsystem::OnMessage(const FString& Message)
{
	LOG_WITH_LOCATION_WARNING(TEXT("Accept Messages : %s"),*Message);
}

void UXG_GameInstanceSubsystem::OnMessageSent(const FString& Message)
{
	LOG_WITH_LOCATION_WARNING(TEXT("Message Sent : %s"),*Message);
}
